﻿using System;
using DataAccess.Repository;

namespace KPI
{
	public partial class Login : BasePage
	{
		protected void Page_Init(object sender, EventArgs e)
		{
			if(TheCurrentLoginUser != null)
			{
				Response.Redirect("~/Index.aspx");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				txtUserName.Focus();
			}
		}

		protected void btnLogin_Click(object sender, EventArgs e)
		{
			var userName = txtUserName.Text.Trim();
			var pwd = txtPwd.Text;

			if(!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(pwd))
			{
				using(var userRepository = new UserRepository())
				{
					var msg = string.Empty;
					var u = userRepository.ValidUserAndGetUser(userName, pwd, out msg);

					if(u != null)
					{
						var theLoginUserInfo = new DataAccess.Models.LoginUserInfo()
						{
							DeptID = 0,
							DeptName = string.Empty,
							RoleName = u.RoleName,
							UserName = u.UserName,
							UserID = u.UserID
						};

						if(chbAutoLogin.Checked)
						{
							theLoginUserInfo.LoginExpires = DateTime.Now.AddMonths(1);
						}

						KPISiteContext.Current.CurrentUser = theLoginUserInfo;

						u.LastLoginTime = DateTime.Now;
						u.LastLoginIP = KPISiteContext.Current.UserHostAddress;

						userRepository.UpdateUser(u, false);

						Response.Redirect("~/Index.aspx");
					}
					else
					{
						ShowMessage(msg, true);
					}
				}
			}
		}
	}
}
